package com.hup.vd.view.customView;

import com.hup.utils.commons.TextUtil;
import com.hup.utils.commons.hardware.MouseUtil;
import com.hup.utils.swing.ComponentUtil;
import com.hup.utils.swing.customView.BaseFileChooser.FixedJFileChooser;
import com.hup.utils.swing.customView.BaseUndoText;
import com.hup.utils.swing.customView.HintTextArea;
import com.hup.vd.model.bo.TaskCreateReq;
import com.hup.vd.view.taskCluster.TaskClusterDialog;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileSystemView;
import javax.swing.undo.UndoManager;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;

/**
 * @author hugan
 * @date 2022/1/11
 */
@Slf4j
public class CreateTaskPanel extends JPanel {
    public JPanel root;
    //
    public JTextArea txtUrl;
    public HintTextArea txtFilePath;
    public JButton btnCreate;
    public JButton btnCreateNStart;
    public JButton btnCreateCluster;
    //
    public SettingPanel pSetting;

    /**
     * 必须设置
     */
    @Setter
    private ViewHandler viewHandler;

    public CreateTaskPanel() {
        $$$setupUI$$$();
        initListener();
    }

    private void initListener() {
        BaseUndoText.initUndo(txtUrl, new UndoManager());
        BaseUndoText.initUndo(txtFilePath, new UndoManager());
        txtUrl.registerKeyboardAction(e -> txtUrl.transferFocus(), KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), JComponent.WHEN_FOCUSED);
        txtFilePath.registerKeyboardAction(e -> txtFilePath.transferFocusBackward(), KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), JComponent.WHEN_FOCUSED);
        txtUrl.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                ComponentUtil.selectAllText(txtUrl);
            }
        });
        txtFilePath.addMouseListener(new MouseAdapter() {
            @SuppressWarnings("DuplicatedCode")
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() != 2 || !MouseUtil.isLeftButton(e)) return;

                //设置初始目录
                File initDir = null;
                String oldFileName = null;
                String filePath = txtFilePath.getText();
                if (!TextUtil.isBlank(filePath)) {
                    File file = new File(filePath);
                    if (!file.isDirectory()) {
                        oldFileName = file.getName();
                        file = file.getParentFile();
                    }
                    if (file != null && file.exists()) initDir = file;
                }
                //省缺为桌面
                if (initDir == null)
                    initDir = FileSystemView.getFileSystemView().getHomeDirectory();

                //打开文件选择器
                FixedJFileChooser fc = new FixedJFileChooser(null);
                fc.setCurrentDirectory(initDir);
                fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                fc.setDialogTitle("保存路径");
                fc.setFileName(oldFileName);
                fc.showDialog(ComponentUtil.getParentWindow(CreateTaskPanel.this), "确定");//标题,提交按钮的字
                //处理结果
                File selectedFile = fc.getSelectedFile();
                if (selectedFile != null) {
                    txtFilePath.setText(selectedFile.getAbsolutePath());
                }
            }
        });
        ActionListener createListener = e -> {
            TaskCreateReq req = new TaskCreateReq();
            req.setUrl(txtUrl.getText());
            String filePath = txtFilePath.getText();
            String ext = FilenameUtils.getExtension(filePath).toLowerCase();//转小写
            if (!filePath.endsWith(ext)) {
                //log.info("filePath={}, {}", filePath, ext);
                filePath = filePath.substring(0, filePath.length() - ext.length()) + ext;
                txtFilePath.setText(filePath);
            }
            req.setFilePath(filePath);
            req.setStartNow(e.getSource() == btnCreateNStart);
            viewHandler.doCreate(req);
        };
        btnCreate.addActionListener(createListener);
        btnCreateNStart.addActionListener(createListener);
        btnCreateCluster.addActionListener(e -> TaskClusterDialog.doShow());
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void $$$setupUI$$$() {
        createUIComponents();
        root.setLayout(new GridBagLayout());
        root.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        final JLabel label1 = new JLabel();
        label1.setText("url");
        GridBagConstraints gbc;
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.EAST;
        root.add(label1, gbc);
        final JLabel label2 = new JLabel();
        label2.setText("保存路径");
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.anchor = GridBagConstraints.EAST;
        root.add(label2, gbc);
        txtUrl = new JTextArea();
        txtUrl.setLineWrap(true);
        txtUrl.setToolTipText("网页或m3u8地址");
        gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.weightx = 1.0;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.insets = new Insets(0, 5, 5, 0);
        root.add(txtUrl, gbc);
        txtFilePath = new HintTextArea();
        txtFilePath.setLineWrap(true);
        txtFilePath.setToolTipText("双击浏览路径");
        gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.insets = new Insets(0, 5, 5, 0);
        root.add(txtFilePath, gbc);
        final JPanel spacer1 = new JPanel();
        gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 3;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.VERTICAL;
        root.add(spacer1, gbc);
        final JPanel panel1 = new JPanel();
        panel1.setLayout(new GridBagLayout());
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.EAST;
        gbc.fill = GridBagConstraints.VERTICAL;
        root.add(panel1, gbc);
        btnCreateNStart = new JButton();
        btnCreateNStart.setText("创建并开始任务");
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.EAST;
        gbc.fill = GridBagConstraints.VERTICAL;
        gbc.ipady = 10;
        gbc.insets = new Insets(8, 8, 0, 0);
        panel1.add(btnCreateNStart, gbc);
        btnCreate = new JButton();
        btnCreate.setText("仅创建任务");
        gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.ipady = 10;
        gbc.insets = new Insets(8, 8, 0, 0);
        panel1.add(btnCreate, gbc);
        btnCreateCluster = new JButton();
        btnCreateCluster.setText("创建批量任务");
        gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.ipady = 10;
        gbc.insets = new Insets(8, 8, 0, 0);
        panel1.add(btnCreateCluster, gbc);
        final JPanel panel2 = new JPanel();
        panel2.setLayout(new GridBagLayout());
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.BOTH;
        root.add(panel2, gbc);
        panel2.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        pSetting = new SettingPanel();
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        panel2.add(pSetting.$$$getRootComponent$$$(), gbc);
    }

    /**
     * @noinspection ALL
     */
    public JComponent $$$getRootComponent$$$() {
        return root;
    }

    private void createUIComponents() {
        root = this;
    }

    public interface ViewHandler {
        void doCreate(TaskCreateReq req);
    }

}
